//
//  LWTabBarBtn.m
//  1.28  weibo
//
//  Created by mac on 15/1/28.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "LWTabBarBtn.h"
#import "LWBadgeBtn.h"

@interface LWTabBarBtn ()

@property (nonatomic,weak) LWBadgeBtn *badgeBtn;
@end
@implementation LWTabBarBtn

- (instancetype)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{

    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}
- (void)setup{
    
    
    self.imageView.contentMode = UIViewContentModeCenter;
    self.titleLabel.textAlignment= NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont systemFontOfSize:13];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    
    //添加提醒按钮
    LWBadgeBtn *badgeBtn = [[LWBadgeBtn alloc] init];
    
    badgeBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
    [self addSubview:badgeBtn];
    self.badgeBtn = badgeBtn;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = contentRect.size.width;
    CGFloat imageH = contentRect.size.height * 0.6;
    CGFloat imageX = 0;
    CGFloat imageY = 0;
    return CGRectMake(imageX, imageY, imageW, imageH);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
//warning 如果相对自定义按钮通过transform进行缩放, 那么不能在自定义按钮中访问self.frame
    // Y = 按钮的高度 - 图片的高度
    CGFloat titleY = contentRect.size.height* 0.6;
    CGFloat titleW = contentRect.size.width;
    CGFloat titleH = contentRect.size.height - contentRect.size.height * 0.6;
    CGFloat titleX = 0;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

- (void)setItme:(UITabBarItem *)itme{

    _itme = itme;
    
    [self setTitle:itme.title forState:UIControlStateNormal];
    [self setImage:itme.image forState:UIControlStateNormal];
    [self setImage:itme.selectedImage forState:UIControlStateSelected];
    //使用KVO监听TabBarItem属性改变
    [itme addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:nil];
    
    
}

- (void)dealloc{

    [_itme removeObserver:self forKeyPath:@"badgeValue"];
}
/**
 *  监听到某个被监听的属性改变时调用
 *
 *  @param keyPath 被监听的属性
 *  @param object  被监听的对象
 *  @param change  属性的改变
 *  @param context 监听时传入的参数
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    NSString *number = change[@"new"];
    self.badgeBtn.badgeValue = number;
}
- (void)layoutSubviews{
    
    [super layoutSubviews];
    self.badgeBtn.x = self.width * 0.5 + 10;
    self.badgeBtn.y = 0;
    
}
- (void)setHighlighted:(BOOL)highlighted{};

@end
